<?php
	//会员领红包页面
	session_start();
	require_once('wxbrower.php');//提示使用微信浏览器打开
	require_once("../includes/public.inc.php");
	//$s=isset($_GET['s'])?$_GET['s']:'';//使用积分领取，不是使用防伪码
	$openid = isset($_GET['openid'])?$_GET['openid']:'';
	$username = isset($_SESSION['username'])?$_SESSION['username']:'';
	$password = isset($_SESSION['password'])?$_SESSION['password']:'';
	
	if (!$username)
	{
		echo "<script>alert('你还没登录呢!');window.parent.location.href='login.php?type=hy';</script>";exit;
	}
	$gift = mysql_fetch_array(mysql_query("select * from ".DBQIAN."gift where id=4 order by id desc limit 1"));
	$user = mysql_fetch_array(mysql_query("select * from ".DBQIAN."users where username='".$username."' order by id desc limit 1"));
	if ($user&&$user['credit'] < ($gift['credit']))
	{
		echo "<script>alert('你的积分不足,不能兑换该奖品！');history.back();</script>";	
		exit;
	}
	if (!isset($_GET['code']))
	{
		$uwxcode=$_GET['uwxcode'];
		$locaurl=urlencode(WEBNAME."user/hylinghongbao.php?s=".$s."&uwxcode=".$uwxcode);//网址解析
		$urls="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx934cb7f852f6c585&redirect_uri=".$locaurl."&response_type=code&scope=snsapi_base#wechat_redirect";
		header("Location:".$urls);exit;
	}
	$code = $_GET['code'];//获取code
	$weixin =  file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx934cb7f852f6c585&secret=94ea78cbbbd72c8a0ecbfc965a497afc&code=".$code."&grant_type=authorization_code");//通过code换取网页授权access_token
	$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
	$array = get_object_vars($jsondecode);//转换成数组
	$openid = $array['openid'];//输出openid
	//echo $openid;exit;
	
	function getAccessToken()
	{
	 $data = json_decode(file_get_contents("access_token.json"));
	    if ($data->expire_time < time()) {
	      $url_get='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx934cb7f852f6c585&secret=94ea78cbbbd72c8a0ecbfc965a497afc';
		  $json=json_decode(curlGet($url_get),true);
		if (!isset($json['errmsg']))
		{
				$access_token = $json['access_token'];
		      if ($access_token) {
		        $data->expire_time = time() + 7000;
		        $data->access_token = $access_token;
		        $fp = fopen("access_token.json", "w");
		        fwrite($fp, json_encode($data));
		        fclose($fp);
		      }
		}
		else {
			echo '获取access_token发生错误：错误代码,微信返回错误信息：';
		}
	    } else {
	      $access_token = $data->access_token;
	    }
		
		return $access_token;
	}
	
	function curlGet($url)
	{
		$curl = curl_init();
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	    curl_setopt($curl, CURLOPT_URL, $url);
	
	    $res = curl_exec($curl);
	    curl_close($curl);
	
	    return $res;
	}
	
	$access_token=getAccessToken();	//echo $access_token;exit;
	$subscribe_msg = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid;
	$subscribe = json_decode(curlGet($subscribe_msg),true);
	$zyxx = $subscribe['subscribe'];
	if($zyxx !== 1)
	{
		header("Location: guanzhu.php");exit;
	}
	//判断是否关注
	$exsit_openid = mysql_fetch_array(mysql_query("select * from ".DBQIAN."users where openid='".$openid."' or (username='".$username."' and password='".$password."') order by id desc limit 1"));
	//$exsit_uopenid = mysql_fetch_array(mysql_query("select * from ".DBQIAN."users where openid='".$openid."' order by id desc limit 1"));
	if(!$exsit_openid)//如果没有注册或者没有openid，跳到选择登录的页面，这是导购的页面不需要做任何的判断
	{
		header("Location: zhengpin.php?s=".$s."&openid=".$openid);exit;//如果两者都没有那么则可以直接跳登录页面
	}
	else 
	{
		if ($exsit_openid)//会员
		{
			//扣分,添加兑换记录
			$in_exchange = mysql_query("insert into ".DBQIAN."exchange (credit,time,username,giftname,qty,post_id,usercredit,nowcredit,status,type) values(".$gift['credit'].",'".date('Y-m-d H:i:s',time())."','".$username."','".$gift['name']."',1,1,".$user['credit'].",".($user['credit']-$gift['credit']).",0,4)");
			$up_user = mysql_query("update ".DBQIAN."users set credit=".($user['credit']-$gift['credit'])." where username='".$username."'");
			if ($in_exchange&&$up_user)
			{
			
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="Keywords" content="正品验证" />
<meta name="Description" content="正品验证" />
<title>香珀蒂</title>
<link rel="stylesheet" href="Public/css/home.min.css" />
</head>
<body class="ui-bar-a">
<div class="load_box" style="margin-top:-230px;">
<div style="position:absolute;top:7px;text-align:left;left:2.5px;">你好，红包已经下发，请注意查收，点击下面按钮登录领取红包吧!更多优惠请进入公众号了解!</div>
<div class="lws_botton"><a href="http://xbd.xf12315.net/main/chaikai.index.php?sk=1445313033&sh=43920&s=<?='0hy'?>&type=hy&openid=<?=$openid?>" >领取红包</a></div>
</div>
<!-- </div> -->
<footer id="footer" class="index_footer">
	<div class="copy">
	&copyright;2015 香珀蒂All Rights Reserved.
	</div>
</footer>
</div>
<!-- /footer -->
</body>
</html>
<?php
			}
		}
	}
?>